package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘柄华
 * Date: 2022-06-21
 * Time: 16:18
 */

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        // 1. 先通过 body 获取到用户提交的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            String html = "<h3>登录失败! 用户名或者密码为空! </h3>";
            resp.getWriter().write(html);
            return;
        }
        // 2. 在数据库中查找用户信息
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null){
            String html = "<h3>登录失败! 用户名或者密码错误! </h3>";
            resp.getWriter().write(html);
            return;
        }
        if (!user.getPassword().equals(password)){
            String html = "<h3>登录失败! 用户名或者密码错误! </h3>";
            resp.getWriter().write(html);
            return;
        }
        // 3. 用户名密码都正确, 设置会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);

        // 4. 重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
